#ifndef SHAREMEMORY_H
#define SHAREMEMORY_H

#include <transfer.h>
#include <QSharedMemory>
#include <cstring>
#include <memory>
#include <QDebug>

class ShareMemoryTransfer : public Transfer {
public:
    virtual ~ShareMemoryTransfer() override {
        qDebug()<<"ddddd";
    }

    virtual size_t send(const QString& topic, const QByteArray& data) override {

        //create
        auto share = autoShareMemory(topic, data.size());

        if(share == nullptr || data.size() > share->size()) {
            return 0;
        }

        share->lock();
        std::memcpy(share->data(), const_cast<char *>(data.data()), data.size());
        share->unlock();

        return data.size();
    }

    virtual QByteArray recive(const QString& topic, int size) override {

        auto share = autoShareMemory(topic, size);

        QByteArray reciveData(size, 0);

        if(share == nullptr || size > share->size()) {
            return reciveData;
        }

        share->lock();
        std::memcpy(reciveData.data(), share->data(), size);
        share->unlock();

        return reciveData;
    }

private:

    std::shared_ptr<QSharedMemory> autoShareMemory(const QString& topic, int size) {
        auto& share = shareMaps[topic];
        if(!share) {
            share = std::make_shared<QSharedMemory>(topic);
            qDebug()<<"create share memory : " << topic;

            if(!share->create(size) && !share->attach()) {
                qDebug()<<"share memory create fial" << size << share->size() <<share->errorString();
            }
        }

        return share;
    }

    QHash<QString, std::shared_ptr<QSharedMemory>> shareMaps;
};

#endif // SHAREMEMORY_H
